package com.jpa.util;


import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author SUCCESS\trule
 *
 */
public class JpaBasics {
	private static EntityManagerFactory entityManagerFactory;
	private static EntityManager entityManager;
	private static Logger logger = LoggerFactory.getLogger(JpaBasics.class);
	 
	static{
		entityManagerFactory = Persistence.createEntityManagerFactory("manager1");
		entityManager = entityManagerFactory.createEntityManager();
	}

	public static <T> T create(T entities) {
		try {
			EntityTransaction transaction = entityManager.getTransaction();
			transaction.begin();
			entityManager.persist(entities);
			transaction.commit();

		} catch (Exception exception) {
			entities = null;
			logger.error("You have a error in method create",exception);
		}

		return entities;
	}
	
	public static <T> Boolean delete(T entities) {
		Boolean deleteStatus = Boolean.TRUE;
		try{
			EntityTransaction transaction = entityManager.getTransaction();
			transaction.begin();
			entityManager.remove(entities);
			transaction.commit();
			
		}catch(Exception exception){
			deleteStatus = Boolean.FALSE;
			logger.error("You have a error in method delete",exception);
		}
		
		return deleteStatus;
	}
	
	public static  <T> Boolean delete(Class<T> entityClass, Object primaryKey) {
		Boolean deleteStatus = Boolean.TRUE;
		try{
			T entityObject = entityManager.find(entityClass, primaryKey);
			if(entityObject != null){
				EntityTransaction transaction = entityManager.getTransaction();
				transaction.begin();
				entityManager.remove(entityObject);
				transaction.commit();
			}
			
		}catch(Exception exception){
			deleteStatus = Boolean.FALSE;
			logger.error("You have a error in method delete",exception);
		}
		
		return deleteStatus;
	}

	public static <T> T find(Class<T> entityClass, Object primaryKey){
		try{
			T entityObject = entityManager.find(entityClass, primaryKey);
			return entityObject;
			
		}catch(Exception exception){
			return null;
		}
	}
}
